<?php

namespace App\Http\Controllers\Web;

use App\Caches\WanSdkStartQueryCache;
use App\Caches\WechatOauthCodeCache;
use App\Commons\CommonConstant;
use App\Http\Controllers\Controller;
use App\Models\Channels;
use App\Models\GameChannel;
use App\Models\Games;
use App\Models\Orders;
use App\Models\Users;
use App\Services\SwitchPay\SwitchPayBase;
use App\Services\WanSdk\WanSdkPayService;
use App\Services\WanSdk\WanSdkService;
use App\Services\WechatApi\WechatApiOauth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use YQ\YqExtend;

class WanSdkTestController extends Controller
{
    public function gameTest(Request $request)
    {
        return view('h5sdk.test', []);
    }

    public function oauthCbTest(Request $request)
    {
        $game_id = $request->input('game_id');
        $channel = Channels::CHANNEL_H5;
        $game_channel = GameChannel::whereRaw("game_id={$game_id} AND channel={$channel}")->first();

        $openid = 'test123123123';
        $wx_openid = 'test123123123';

        $game = Games::where('game_id', $game_id)->first()->toArray();
        return view('h5sdk.index', [
            'game'         => $game,
            'game_channel' => $game_channel,
            'openid'       => $openid,
            'wx_openid'    => $wx_openid,
            'query'        => ['aaa'=>'ddd'],
        ]);
    }

    public function clickWxpayJssdk(Request $request, $appid)
    {
        $cb_url = config('app.url') . "/h5sdk/pay_test?appid={$appid}";
        $url = WechatApiOauth::getInstance()->getUserOauthUrl($appid, $cb_url, 'snsapi_base', 'pay');

        return redirect()->away($url);
    }

    public function payTest(Request $request)
    {
        $appid = $request->input('appid') ?? '';
        $code = $request->input('code') ?? '';
        $order = Orders::find(441);
        if (!empty($appid) && !empty($code)) {
            $order = WanSdkPayService::getInstance()->getOrderByJssdkAccessToken($appid, $code);
        }

        if (is_numeric($order)) {
            return view('h5sdk.pay_fail', []);
        }

        $game = Games::where('game_id', $order->game_id)->first();
        return view('h5sdk.pay', [
            'order'        => $order,
            'pay_platform' => Orders::PAY_PLATFORM_WAN_WECHAT_JSSDK,
            'game'         => $game,
            'game_url'     => WanSdkService::getInstance()->getGameUrl($order->game_id),
        ]);
    }
}
